package simpledb.tx.recovery;

import static simpledb.tx.recovery.LogRecord.*;
import java.util.Iterator;
import simpledb.log.BasicLogRecord;
import simpledb.server.SimpleDB;

/**
 * A class that provides the ability to read records from the log in reverse
 * order. Unlike the similar class {@link simpledb.log.LogIterator LogIterator},
 * this class understands the meaning of the log records.<br>
 * 提供以相反顺序从日志中读取记录的类。 与类似的{@link simpledb.log.LogIterator LogIterator}
 * 类不同，此类理解日志记录的含义。
 * 
 * @author Edward Sciore
 */
class LogRecordIterator implements Iterator<LogRecord> {
  private Iterator<BasicLogRecord> iter = SimpleDB.logMgr().iterator();

  /**
   * With reference to {@link simpledb.log.LogIterator#hasNext() hasNext()}
   */
  public boolean hasNext() {
    return iter.hasNext();
  }

  /**
   * Constructs a log record from the values in the current basic log record.
   * The method first reads an integer, which denotes the type of the log
   * record. Based on that type, the method calls the appropriate LogRecord
   * constructor to read the remaining values.<br>
   * 根据当前基本日志记录中的值来构造日志记录，这个方法首先读取一个整数，它表示日志记录的类型。基于该类型，此方法将调用对应的LogRecord
   * 构造函数来读取日志记录的值.
   * 
   * @return the next log record, or null if no more records 下一个日志记录，如果没有更多的记录则为null
   */
  public LogRecord next() {
    BasicLogRecord rec = iter.next();
    int op = rec.nextInt();
    switch (op) {
      case CHECKPOINT:
        return new CheckpointRecord(rec);
      case START:
        return new StartRecord(rec);
      case COMMIT:
        return new CommitRecord(rec);
      case ROLLBACK:
        return new RollbackRecord(rec);
      case SETINT:
        return new SetIntRecord(rec);
      case SETSTRING:
        return new SetStringRecord(rec);
      default:
        return null;
    }
  }

  public void remove() {
    throw new UnsupportedOperationException();
  }
}
